package cn.wjh.business.service.impl;

import cn.wjh.business.domain.Competition;
import cn.wjh.business.domain.CompetitionSign;
import cn.wjh.business.domain.KeyValue;
import cn.wjh.business.domain.Works;
import cn.wjh.business.mapper.CompetitionMapper;
import cn.wjh.business.service.ICollectService;
import cn.wjh.business.service.ICompetitionService;
import cn.wjh.business.service.ICompetitionSignService;
import cn.wjh.business.service.IWorksService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 比赛Service业务层处理
 *
 * @author jiraWu
 * @date 2023-10-17
 */
@Service
public class CompetitionServiceImpl extends ServiceImpl<CompetitionMapper, Competition> implements ICompetitionService {
	@Resource
	private CompetitionMapper competitionMapper;
	@Resource
	private ISysUserService userService;
	@Resource
	private ICollectService collectService;
	@Resource
	private ICompetitionSignService competitionSignService;

	@Resource
	private IWorksService worksService;

	/**
	 * 查询比赛
	 *
	 * @param competitionId 比赛主键
	 * @return 比赛
	 */
	@Override
	public Competition selectCompetitionByCompetitionId(Long competitionId) {
		Competition competition = competitionMapper.selectCompetitionByCompetitionId(competitionId);
		if (StringUtils.isNull(competition)) return competition;
		if (competition.getJudgeIds().isEmpty()) return competition;
		/*比赛评委*/
		LambdaQueryWrapper<SysUser> selectWrapper = new QueryWrapper<SysUser>().lambda()
				.select(SysUser::getNickName, SysUser::getAvatar, SysUser::getUserId, SysUser::getRemark)
				.in(SysUser::getUserId, competition.getJudgeIds());
		List<SysUser> users = userService.list(selectWrapper);
		competition.setJudges(users);
		/*收藏数量*/
		Long count = collectService.countByDataIdAndType(competitionId, "competition");
		competition.setCollect(count);
		return competition;
	}

	/**
	 * 查询比赛列表
	 *
	 * @param competition 比赛
	 * @return 比赛
	 */
	@Override
	public List<Competition> selectCompetitionList(Competition competition) {
		List<Competition> competitions = competitionMapper.selectCompetitionList(competition);
		/*收藏数量*/
		competitions.forEach(c -> {
			c.setCollect(collectService.countByDataIdAndType(c.getCompetitionId(), "competition"));
		});
		return competitions;
	}

	/**
	 * 新增比赛
	 *
	 * @param competition 比赛
	 * @return 结果
	 */
	@Override
	public int insertCompetition(Competition competition) {
		competition.setCreateTime(DateUtils.getNowDate());//创建时间
		competition.setDeptId(SecurityUtils.getDeptId());//部门Id
		competition.setCreateBy(SecurityUtils.getUsername());//创建人
		validateDateTime(competition);//校验时间
		return competitionMapper.insert(competition);
	}

	/**
	 * 修改比赛
	 *
	 * @param competition 比赛
	 * @return 结果
	 */
	@Override
	public int updateCompetition(Competition competition) {
		competition.setUpdateTime(DateUtils.getNowDate());//修改时间
		competition.setUpdateBy(SecurityUtils.getUsername());//创建人
		validateDateTime(competition);//校验时间
		return competitionMapper.updateById(competition);
	}

	/**
	 * 批量删除比赛
	 *
	 * @param competitionIds 需要删除的比赛主键
	 * @return 结果
	 */
	@Override
	public int deleteCompetitionByCompetitionIds(Long[] competitionIds) {
		return competitionMapper.deleteCompetitionByCompetitionIds(competitionIds);
	}

	/**
	 * 删除比赛信息
	 *
	 * @param competitionId 比赛主键
	 * @return 结果
	 */
	@Override
	public int deleteCompetitionByCompetitionId(Long competitionId) {
		return competitionMapper.deleteCompetitionByCompetitionId(competitionId);
	}

	@Override
	public List<KeyValue> listKeyValue() {
		List<Competition> list = this.list(new QueryWrapper<Competition>().lambda()
				.select(Competition::getCompetitionId, Competition::getTitle, Competition::getJudgeIds));
		return list.stream().map(KeyValue::new).collect(Collectors.toList());
	}

	/**
	 * 获取我参加的比赛
	 *
	 * @param competition
	 * @return
	 */
	@Override
	public List<Competition> myJoinCompetition(Competition competition) {
		List<Competition> competitions = new ArrayList<>();
		Long userId = SecurityUtils.getUserId();
		CompetitionSign competitionSign = new CompetitionSign();
		competitionSign.setUserId(userId);
		List<CompetitionSign> competitionSigns = competitionSignService.selectCompetitionSignList(competitionSign);//自己的所有报名信息
		if (competitionSigns.isEmpty()) return competitions;
		List<Long> competitionIds = competitionSigns.stream().map(CompetitionSign::getCompetitionId).collect(Collectors.toList());//所有比赛Id

		/*构造条件*/
		LambdaQueryWrapper<Competition> selectWrapper = new QueryWrapper<Competition>().lambda()
				.like(StringUtils.isNotEmpty(competition.getTitle()), Competition::getTitle, competition.getTitle())
				.in(Competition::getCompetitionId, competitionIds);
		List<Competition> list = this.list(selectWrapper);

		if (list.isEmpty()) return competitions;
		Works works = new Works();
		works.setUserId(userId);
		List<Works> worksList = worksService.myWorks(works);//我的作品列表
		list.forEach(item -> {
			worksList.forEach(w -> {
				/*比赛Id=作品里的比赛Id*/
				if (item.getCompetitionId().equals(w.getCompetitionId())) {
					item.setIsPublishWorks(true);
				}
			});
		});
		return list;
	}

	@Override
	public List<Competition> getMyJudgementCompetitionList(Competition competition) {
		List<Competition> competitions = selectCompetitionList(competition);
		if (null == competitions || competitions.isEmpty()) return competitions;
		Long userId = SecurityUtils.getUserId();
		List<Competition> list = new ArrayList<>();
		competitions.forEach(c -> {
			List<Long> judgeIds = c.getJudgeIds();
			if (judgeIds.contains(userId)) {
				list.add(c);
			}
		});
		return list;
	}

	/**
	 * 校验时间
	 */
	private static void validateDateTime(Competition competition) {
//		Date currentDate = competition.getCreateTime();//当前时间
		Date startTime = competition.getStartTime();//比赛开始时间
		Date endTime = competition.getEndTime();//比赛结束时间
		Date signUpStartTime = competition.getSignStartTime();//报名开始时间
		Date signUpEndTime = competition.getSignEndTime();//报名结束时间
		if (!signUpStartTime.before(signUpEndTime)) {
			throw new ServiceException("报名开始时间必须要在报名结束时间之前");
		}

		if (!startTime.before(endTime)) {
			throw new ServiceException("比赛开始时间必须在比赛结束时间之前");
		}

		if (!signUpStartTime.before(startTime)) {
			throw new ServiceException("报名开始时间必须在比赛开始时间之前");
		}

	}
}
